from typing import Sequence

from app.crud.base_crud import BaseCRUD
from app.models.region import Region
from app.schemas.query_schema import BaseQueryIn
from app.schemas.region_schema import RegionCreate, RegionUpdate


class RegionCRUD(BaseCRUD[Region, RegionCreate, RegionUpdate]):
    async def get_all(self,query_in: BaseQueryIn = None,) -> Sequence[Region]:
        """
        获取所有启用的
        :param query_in: 自定义查询
        :return:
        """
        results = (await self.context.dynamic_query(query_in)
                   .include(self.model.children, criteria=(Region, Region.is_delete == False), recursion_depth=3)
                   .to_list())

        # 获取结果中所有ID（不包含children属性中的）
        result_ids = {item.id for item in results}

        # 使用了预先加载，children同时存在于顶层和子级
        # 没有parent_id值，说明为顶级
        # 父级id不在当前result_ids中，也要放置于顶层，用于table动态搜索
        top_level = [
            item
            for item in results
            if item.parent_id is None or item.parent_id not in result_ids
        ]

        return top_level


